package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Brand;
import com.itheima.goods.service.BrandService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author cai xu dong
 * @date 2021/5/9 20:04
 */
@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    @GetMapping
    public Result findAll() {
        List<Brand> list = brandService.list();
        return new Result(true,20000,"查询成功",list);
    }

    @PostMapping
    public Result add(@RequestBody Brand brand) {
        brandService.save(brand);
        return new Result(true,20000,"增加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result search(@PathVariable("page") Long current, @PathVariable("size") Long size) {
        Page<Brand> Page = new Page<>(current, size);
        brandService.page(Page);
        return new Result(true, 20000, "查询成功", Page);
    }

    @PostMapping("search2/{page}/{size}")
    public Result search2(@PathVariable("page") Long current, @PathVariable("size") Long size,
                          @RequestBody Map<String, String>searchMap) {
        Page<Brand> pages = new Page<>(current, size);
        LambdaQueryWrapper<Brand> wrapper = Wrappers.<Brand>lambdaQuery();
        wrapper.eq(Brand::getId,searchMap.get("id"));
        wrapper.like(Brand::getName,searchMap.get("name"));
        Page<Brand> page = brandService.page(pages, wrapper);
        return new Result(true,20000,"查询成功",page);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable int id) {
        Brand byId = brandService.getById(id);
        return new Result(true, 20000, "查询成功", byId);
    }
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") int id,@RequestBody Brand brand){
        LambdaQueryWrapper<Brand> wrapper = Wrappers.<Brand>lambdaQuery();
        LambdaQueryWrapper<Brand> eq = wrapper.eq(Brand::getId, id);
        boolean update = brandService.update(brand, eq);
        return new Result(true,20000,"更新成功",update);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int id) {
        brandService.removeById(id);
        return new Result(true, 20000, "删除成功");
    }
}
